package org.example.jdbcOperator.util;

import javax.sql.DataSource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.LinkedList;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.logging.Logger;

public class DbUtil {

    private final String dbUrl = "jdbc:mysql://39.106.36.89:3306/tmp_data";
    private final String dbUser = "tmp_data";
    private final String dbPassword = "tyTmpData";
    private final String dbDriver = "com.mysql.cj.jdbc.Driver";
//    private Connection connection = null;

    private ArrayBlockingQueue<Connection> pool = null;
    private static final int POOL_MAX = 5;

    private static volatile DbUtil instance = null;

    public static DbUtil getInstance() {
        if (instance == null) {
            synchronized (DbUtil.class) {
                if (instance == null) {
                    instance = new DbUtil();
                }
            }
        }
        return instance;
    }

    public synchronized Connection getConnection() {
        Connection connection = null;
        try {
            if (pool == null) {
                synchronized (DbUtil.class) {
                    if (pool == null) {
                        pool = new ArrayBlockingQueue<>(POOL_MAX);
                        Class.forName(dbDriver);
                        for (int i = 0; i < POOL_MAX; i++) {
                            pool.add(DriverManager.getConnection(dbUrl, dbUser, dbPassword));
                        }
                        System.out.println("mysql add POOL_MAX connection to pool");
                    }
                }
            }
            connection = pool.take();;
            System.out.println("mysql connect success, now: [" + pool.size() + "]");
        } catch (SQLException | ClassNotFoundException | InterruptedException e) {
            throw new RuntimeException(e);
        }
        return connection;
    }

    public void releaseConnection(Connection connection) {
        pool.offer(connection);
        System.out.println("mysql connect release to pool, now: [" + pool.size() + "]");
    }
}
